package cn.fintecher.gis.service;

import cn.fintecher.gis.entity.*;
import cn.fintecher.gis.enums.CommonShow;
import cn.fintecher.gis.enums.FlowType;
import cn.fintecher.gis.enums.MessageType;
import cn.fintecher.gis.model.request.BusinessFileRequest;
import cn.fintecher.gis.model.request.FlowApplyRequest;
import cn.fintecher.gis.model.request.GrantRequest;
import cn.fintecher.gis.model.request.LayerInfoCreateRequest;
import cn.fintecher.gis.model.session.SessionModel;
import cn.fintecher.gis.utils.BeanUtils;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 18:01 2019/4/29
 */

@Service("grantInfoService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class GrantInfoService extends BaseService {
    /**
     * 新增报地信息
     */
    public void addGrantInfo(GrantRequest request, SessionModel model) throws Exception {
        GrantInfo grantInfo = new GrantInfo();
        LocalDate dateTime = LocalDate.parse(request.getGrantTime(), DateTimeFormat.forPattern("yyyy-MM-dd"));
        BeanUtils.copyPropertiesIgnoreNull(request, grantInfo);
        grantInfo.setGrantTime(dateTime.toDate());
        if (Objects.nonNull(request.getLayerBaseRequest())) {
            LayerInfoCreateRequest layerInfoCreateRequest = new LayerInfoCreateRequest();
            BeanUtils.copyPropertiesIgnoreNull(request.getLayerBaseRequest(), layerInfoCreateRequest);
            List<String> styleNames = new ArrayList<>();
            styleNames.add(request.getLayerBaseRequest().getStyleName());
            layerInfoCreateRequest.setStyleNames(styleNames);
            BusinessLayer businessLayer = getLayerInfo(layerInfoCreateRequest, FlowType.GRANT, model);
            grantInfo.setBusinessLayer(businessLayer);
        }
        Set<DistrictInfo> infoSet = getDistrictInfoByIds(request.getRegions());
        grantInfo.setRegions(infoSet);
        reportInfoRepository.findById(request.getReportId()).ifPresent(reportInfo -> {
            grantInfo.setReportInfo(reportInfo);
            return;
        });
        GrantInfo info = grantInfoRepository.save(grantInfo);
        if (Objects.nonNull(request.getFileIds()) && !request.getFileIds().isEmpty()) {
            List<GrantFile> list = new ArrayList<>();
            for (String fileId : request.getFileIds()) {
                GrantFile grantFile = new GrantFile();
                grantFile.setGrantId(info.getId());
                grantFile.setFileId(fileId);
                list.add(grantFile);
            }
            grantFileRepository.saveAll(list);
        }
        //添加流程申请
        FlowApplyRequest flowApplyRequest = new FlowApplyRequest();
        flowApplyRequest.setApplyId(info.getId());
        flowApplyRequest.setApplyUserId(model.getId());
        flowApplyRequest.setType(FlowType.GRANT);
        if (info.getWhether().equals(CommonShow.YES)) {
            flowApplyRequest.setNextUserId(request.getNextUserId());
        }
        flowApplyRequest.setWhether(info.getWhether());
        flowService.flowApply(flowApplyRequest, MessageType.GRANT);
    }


    /**
     * 根据code查询批地信息
     *
     * @param code
     * @return
     */
    public List<GrantInfo> getGrantInfoByCode(String code) {
        Iterator<GrantInfo> infoIterator = grantInfoRepository.findAll(QGrantInfo.grantInfo.code.like("%".concat(code).concat("%"))).iterator();
        List<GrantInfo> list = new ArrayList<>();
        while (infoIterator.hasNext()) {
            GrantInfo grantInfo = infoIterator.next();
            if (!flowService.exitRefuse(grantInfo.getId())) {
                list.add(grantInfo);
            }
        }
        return list;
    }


    /**
     * 根据id查询批地信息
     *
     * @param id
     * @return
     */
    public GrantInfo getGrantInfoById(String id) {
        GrantInfo info = new GrantInfo();
        grantInfoRepository.findById(id).ifPresent(grantInfo -> {
            BeanUtils.copyPropertiesIgnoreNull(grantInfo, info);
            return;
        });
        return info;
    }


    /**
     * 再次添加文件
     *
     * @param request
     */
    public void editBusinessFile(BusinessFileRequest request) {
        if (request.getFlowType().equals(FlowType.REPORT)) {//报地文件
            List<ReportFile> list = new ArrayList<>();
            for (String fileId : request.getFileIds()) {
                ReportFile reportFile = new ReportFile();
                reportFile.setFileId(fileId);
                reportFile.setReportId(request.getBusinessId());
                list.add(reportFile);
            }
            reportFileRepository.saveAll(list);
        } else if (request.getFlowType().equals(FlowType.GRANT)) {//批地文件
            List<GrantFile> list = new ArrayList<>();
            for (String fileId : request.getFileIds()) {
                GrantFile grantFile = new GrantFile();
                grantFile.setFileId(fileId);
                grantFile.setGrantId(request.getBusinessId());
                list.add(grantFile);
            }
            grantFileRepository.saveAll(list);
        } else if (request.getFlowType().equals(FlowType.EXPROPRIA)) {//征地文件
            List<ExpropriationFile> list = new ArrayList<>();
            for (String fileId : request.getFileIds()) {
                ExpropriationFile expropriationFile = new ExpropriationFile();
                expropriationFile.setFileId(fileId);
                expropriationFile.setExpId(request.getBusinessId());
                list.add(expropriationFile);
            }
            expropriationFileRepository.saveAll(list);
        } else if (request.getFlowType().equals(FlowType.SUPPLY)) {
            List<SupplyFile> list = new ArrayList<>();
            for (String fileId : request.getFileIds()) {
                SupplyFile supplyFile = new SupplyFile();
                supplyFile.setFileId(fileId);
                supplyFile.setSupplyId(request.getBusinessId());
                list.add(supplyFile);
            }
            supplyFileRepository.saveAll(list);
        }
    }
}
